import pandas as pd
import numpy as np


pd.set_option("display.width", 200)
df = pd.read_csv('test.csv', index_col=['Date'])



def test_iter_row():
    """错位赋值"""
    df['close_max3'] = df['Close'].rolling(window=3).max()
    for i in range(0, len(df)-3):
        row = df.iloc[i]
        #print(row)
        df.ix[i, 'after_close_max3'] = df.ix[i+3, 'close_max3']

    print(df)

def test_apply():
    def _my_max(x):
        # print(type(x)) numpy.ndarray
        return np.sum(x)

    df['close_max3'] = df['Close'].rolling(window=3).apply(_my_max)
    print(df)


def test_apply2():
    def _my_max(x, *args):
        print(x, len(*args))
        # print(type(x)) numpy.ndarray
        return np.sum(x)

    df['close_max3'] = df['Close'].rolling(window=3).apply(_my_max, (df,))
    print(df)

def test_apply3():
    def _mean_ratio(x):
        if x[0] > 0.0001:
            return ( x[1] / x[0] - 1) * 100
        else:
            return None
    df['mean3'] = df['Close'].rolling(window=3).mean()

    df['mean3_ratio'] = df['mean3'].rolling(window=2).apply(_mean_ratio)
    print(df)


def test_split():
    print(df)
    for i in range(0, len(df)):
        print(df[i:i+1])
        print(df[i:i+1].iloc[0]['Open'])

def apply_seria_test():
    df = pd.DataFrame(data={'A': [[2, 4, 8, 16], [100, 200], [10, 20, 30]], 'B': [['a', 'b', 'c'], ['jj', 'kk'], ['ccc']]},
        index=['I', 'II', 'III'])
    print(df)
    def SeriesFromSubList(aList):
        print("alist = ", aList)
        return pd.Series(aList)
    # df.apply(SeriesFromSubList)
    for ind, row in df.iterrows():
        print("--", ind, row, row.apply(SeriesFromSubList))
    df_orgz = pd.concat(dict([(ind, row.apply(SeriesFromSubList)) for ind, row in df.iterrows()]))
    print(df_orgz)

if __name__ == '__main__':
    # test_iter_row()
    #test_apply3()
    # test_split()
    apply_seria_test()